import React, {PropsWithChildren, useMemo, useState} from 'react'
import {Text, View} from "@tarojs/components";
import styles from "./ScratchDocumentItemCell.module.sass"
import {Button, Cell, ConfigProvider, Input, InputNumber, Picker, Space} from "@nutui/nutui-react-taro";
import Taro from "@tarojs/taro";
import {ArrowDown, ArrowUp, Edit} from "@nutui/icons-react-taro";
import {ScratchDocumentItem} from "../store/ScratchDocumentStore";
import {GoodsUnitResponse} from "../apis/GoodsApi";

export interface ScratchDocumentItemCellProps extends PropsWithChildren {
    data: ScratchDocumentItem

    onDelete(): Promise<void>

    showAmount: boolean
    showNote: boolean

    onUpdateAmount(amount: number, unitId?: number,): Promise<void>

    onUpdateNote(note?: string): Promise<void>
}

const ScratchDocumentItemCell: React.FC<ScratchDocumentItemCellProps> = (props) => {
    let data = props.data;
    const [showUnitPicker, setShowUnitPicker] = useState(false)
    const [loading, setLoading] = useState(false)
    const basicUnit = useMemo(() => {
        return data.units.find(it => it.basicMultiple === 0)
    }, [data]);
    const currentUnit = useMemo(() => {
        return data.units?.find(it => it.id === data.unit?.id) ?? basicUnit
    }, [data]);
    let number = useMemo(() => {
        return data.subGoods ? data.barcode + "|" + data.subGoods.number : data.barcode
    }, [data])
    let name = useMemo(() => {
        return data.subGoods ? data.subGoods.name + `（${data.name}）` : data.name
    }, [data])

    async function doUpdateAmount(amount: number, unitId?: number) {
        setLoading(true)
        try {
            await props.onUpdateAmount!(amount, unitId)
        } finally {
            setLoading(false)
        }
    }

    return <>
        <Cell title={<Text className={styles.title}>{name}</Text>}
              onClick={() => {
                  Taro.navigateTo({url: `/pages/goodsDetail?id=${data.id}`})
              }}
            // @ts-ignore
              onLongPress={async () => {
                  let result = (await Taro.showModal({
                      title: `确定要删除“${name}“吗`,
                  }))
                  if (result.confirm)
                      await props.onDelete()
              }}
              description={<>
                  <View style={{display: "flex", flexDirection: "column",}}>
                      <Text>{number}</Text>
                      {props.showAmount && <Space align={"center"}>
                          <ConfigProvider theme={{
                              nutuiInputnumberButtonWidth: '24px',
                              nutuiInputnumberButtonHeight: '24px',
                              nutuiInputnumberButtonBackgroundColor: `#f4f4f4`,
                              nutuiInputnumberInputBackgroundColor: '#fff',
                              nutuiInputnumberInputMargin: '0 2px',
                          }}>
                          <InputNumber value={data.amount}
                                       async
                                       readOnly={loading}
                                       onClick={event => {
                                           event.stopPropagation()
                                       }}
                                       onChange={async value => {
                                           doUpdateAmount(Number(value), data.unit?.id)
                                       }}/>
                          </ConfigProvider>
                          {!!data.units.length && <Button fill={"none"} onClick={(e) => {
                              e.stopPropagation()
                              setShowUnitPicker(true)
                          }} rightIcon={showUnitPicker ? <ArrowUp/> :
                              <ArrowDown/>}><Text>{currentUnit?.name}{currentUnit && basicUnit && basicUnit?.id !== currentUnit?.id ? `=${(data.amount??0) * currentUnit.basicMultiple}${basicUnit.name}` : ""}</Text></Button>}
                      </Space>}
                      {props.showNote && <View style={{display: "flex", flexDirection: "row", alignItems: "center"}}
                                               onClick={async (event) => {
                                                   event.stopPropagation()
                                                   let result = await Taro.showModal({
                                                       title: "请输入备注",
                                                       // @ts-ignore
                                                       editable: true,
                                                   });
                                                   if (result.confirm) {
                                                       if (props.onUpdateNote) {
                                                           try {
                                                               setLoading(true)
                                                               // @ts-ignore
                                                               await props.onUpdateNote(result.content)

                                                           } catch (e) {

                                                           } finally {
                                                               setLoading(false)
                                                           }
                                                       }
                                                   }
                                               }}>
                          {<Edit/>}
                          {<Input value={data.note} type={"text"} readOnly placeholder={"备注"}/>}
                      </View>}

                  </View>
              </>}/>
        <Picker title={"请选择单位"} visible={showUnitPicker}
                options={[
                    data.units.map(unit => {
                        let text = unit.name;
                        if (unit.basicMultiple !== 0 && !!basicUnit) {
                            text += `=${unit.basicMultiple}${basicUnit.name}`
                        }
                        return {
                            value: unit.id,
                            text,
                        }
                    })
                ]}
                onClose={() => setShowUnitPicker(false)}
                onConfirm={async (_, selectedValue) => {
                    await doUpdateAmount(data.amount ?? 1, Number(selectedValue[0]))
                }}/>
    </>
}

export default ScratchDocumentItemCell


